package lk.util;

import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * FTP服务工具类
 *
 */
public class FtpUtil {

    /**
     * FTP地址
     **/
    public static String FTP_ADDRESS;

    /**
     * FTP端口
     **/
    public static int FTP_PORT = FTPClient.DEFAULT_PORT;

    /**
     * FTP用户名
     **/
    public static String FTP_USERNAME;

    /**
     * FTP密码
     **/
    public static String FTP_PASSWORD;

    /**
     * FTP基础目录
     **/
    public static String FTP_BASE_PATH;

    public static int FTP_TIME_OUT;
    public static int FTP_BUFFER_SIZE;

    /**
     * 本地字符编码
     **/
    public static String LOCAL_CHARSET = "GBK";

    /**
     * 上传文件
     *
     * @param in       文件输入流
     * @param filePath 文件上传路径
     * @param fileName 文件名称
     * @throws IOException IO 异常
     */
    public static void upload(InputStream in, String filePath, String fileName, FTPClient ftp) throws IOException {
        filePath = createDirectory(filePath, ftp);
        if (!ftp.changeWorkingDirectory(filePath)) {
            System.out.println("上传时，切换到目录失败:" + filePath);
        }
        ftp.storeFile(new String(fileName.getBytes(LOCAL_CHARSET), FTPClient.DEFAULT_CONTROL_ENCODING), in);
    }

    /**
     * 下载文件
     *
     * @param os       输出流
     * @param ftpPath  文件在 FTP 的位置
     * @param fileName 文件名称
     */
    public static void downloadFiles(OutputStream os, String ftpPath, String fileName, FTPClient ftp) {
        ftp.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据
        try {
            if (!ftp.changeWorkingDirectory(ftpPath)) {
                System.out.println("目录切换失败:" + ftpPath);
                return;
            }
            ftp.setControlEncoding("GBK");
            ftp.retrieveFile(new String(fileName.getBytes(LOCAL_CHARSET), FTPClient.DEFAULT_CONTROL_ENCODING), os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在服务器上创建多级目录
     *
     * @param dirPath 上传目录路径
     * @return 处理后的目录
     */
    private static String createDirectory(String dirPath, FTPClient ftp) throws IOException {
        dirPath = dirPath.replaceAll("\\\\", "/");
        System.out.println(dirPath);
        String[] fileDirectory = dirPath.split("/");
        for (String directory : fileDirectory) {
            if ("".equals(directory)) {
                continue;
            }
            if (!ftp.makeDirectory(directory)) {
                System.out.println("创建目录失败:" + directory);
            }
            if (!ftp.changeWorkingDirectory(directory)) {
                System.out.println("切换目录失败:" + directory);
                throw new IOException();
            }
        }
        return dirPath;
    }


}